<template>
  <view class="health-container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <image src="/static/logo.png" mode="aspectFit" class="logo"></image>
      <text class="title">健康监测</text>

    </view>


    <!-- 内容区 -->
    <scroll-view scroll-y class="content">
      <!-- 睡眠和运动概览 -->
      <view class="overview-cards">
        <view class="overview-card sleep" @click="navigateToDetail('sleep')">
          <view class="card-content">
            <view class="card-title">睡眠时长</view>
            <view class="card-value">{{ sleepData?.total || 0 }}<text class="unit">小时</text></view>
            <view class="card-footer">
              <text class="time">{{ sleepData?.bedTime || '--:--' }}</text>
              <text class="label">入睡时间</text>
            </view>
          </view>
          <view class="card-icon">
            <uni-icons type="moon" size="24" color="#409EFF">🌙</uni-icons>
          </view>
        </view>
        
        <view class="overview-card activity" @click="navigateToDetail('activity')">
          <view class="card-content">
            <view class="card-title">今日步数</view>
            <view class="card-value">{{ activityData?.steps || 0 }}<text class="unit">步</text></view>
            <view class="card-footer">
              <text class="distance">{{ activityData?.distance || 0 }}<text class="unit">公里</text></text>
              <text class="label">运动距离</text>
            </view>
          </view>
          <view class="card-icon">
            <uni-icons type="footprint" size="24" color="#67C23A">🏃‍♀️</uni-icons>
          </view>
        </view>
      </view>

      <!-- 实时监测 -->
      <view class="tab-content">
        <view class="monitor-cards">
          <healthCard v-for="(item, index) in monitorData" :key="index" :title="item.title" :status="item.status"
            :statusClass="item.statusClass" :value="item.value" :unit="item.unit" :trend="item.trend"
            :footerText="item.footerText" :footerButton="item.footerButton" />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useHealthData } from '../../store/modules/useHealthData'
import { useBindingStore } from '../../store/modules/useBindingStore'
import { useUserStore } from '../../store/modules/useUserStore'
import healthCard from '../../components/healthCard.vue'



// 初始化健康数据存储
const healthStore = useHealthData()
const bindingStore = useBindingStore()
const userStore = useUserStore()

// 获取当前绑定的用户ID
// const currentUserId = computed(() => bindingStore.getCurrentBinding?.userId)
const currentUserId = ref(userStore.userData.role=='older'?userStore.curUserId:bindingStore.getCurBindingId)
healthStore?.setCurUserId(currentUserId.value)

// 获取睡眠数据
const sleepData = computed(() => {
  const data = healthStore.getSleepDetailData.day || {
    sleepScore: 88,
    mainSleep: "8小时0分钟",
    sleepRange: "22:30 - 06:30",
    totalSleep: "8小时0分钟",
    sleepStages: []
  };
  
  // 从 sleepRange 中提取入睡时间
  const bedTime = data.sleepRange?.split(' - ')[0] || '--:--';
  
  // 从 totalSleep 中提取总睡眠时长（小时）
  const totalHours = parseFloat(data.totalSleep) || 0;
  
  // 从 sleepStages 中获取深睡比例
  const deepSleepStage = data.sleepStages?.find(stage => stage.name === "深睡");
  const deepSleepPercent = deepSleepStage?.percent || 0;

  return {
    total: totalHours,
    deepSleepPercent: deepSleepPercent,
    bedTime: bedTime,
    awakeTimes: 0, // API 返回数据中没有这个字段
    sleepScore: data.sleepScore
  };
});

// 获取活动数据
const activityData = computed(() => {
  const data = healthStore.getActivityDetailData.day || {
    steps: 8000,
    distance: 5.2,
    calories: 350,
    activeMinutes: 45
  };
  return data;
});

// 计算血氧状态
const bloodOxygenStatus = computed(() => {
  const value = healthStore.realtimeHealthData.bloodOxygen
  if (value >= 95) return '正常'
  if (value >= 90) return '偏低'
  return '异常'
})

// 计算心率状态
const heartRateStatus = computed(() => {
  const value = healthStore.realtimeHealthData.heartRate
  if (value >= 60 && value <= 100) return '正常'
  if (value > 100) return '偏高'
  if (value < 60) return '偏低'
  return '异常'
})

// 计算血压状态
const bloodPressureStatus = computed(() => {
  const systolic = healthStore.realtimeHealthData.bloodPressureHigh
  const diastolic = healthStore.realtimeHealthData.bloodPressureLow
  if (systolic < 90 || diastolic < 60) return '低血压'
  if (systolic >= 140 || diastolic >= 90) return '高血压'
  if (systolic >= 120 || diastolic >= 80) return '正常偏高'
  return '正常'
})

// 获取当前心率和变化趋势
const currentHeartRate = computed(() => healthStore.realtimeHealthData.heartRate)
const heartRateTrend = computed(() => {
  // 使用默认趋势数据
  return { type: 'up', value: 2 }
})

// 获取当前血氧
const currentBloodOxygen = computed(() => healthStore.realtimeHealthData.bloodOxygen)

// 获取当前血压
const currentBloodPressure = computed(() => ({
  systolic: healthStore.realtimeHealthData.bloodPressureHigh,
  diastolic: healthStore.realtimeHealthData.bloodPressureLow
}))


// 刷新活动数据
const refreshActivityData = async () => {
  uni.showLoading({ title: '刷新中...' })
  try {
    if (!currentUserId.value) {
      throw new Error('未找到绑定的用户')
    }
    await healthStore.fetchRealtimeData(currentUserId.value)
    uni.showToast({ title: '数据已更新', icon: 'success' })
  } catch (error) {
    uni.showToast({
      title: error.message || '刷新数据失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

const navigateToDetail = (type) => {
  console.log(`Navigating to detail page for: ${type}`);
  const routes = {
    sleep: '/pages/common/health/viewSleep',
    heartRate: '/pages/common/health/viewHeartRate',
    activity: '/pages/common/health/viewExerciseStep',
    bloodPressure: '/pages/common/health/bloodPressure',
    bloodOxygen: '/pages/common/health/bloodOxygenMonitor'
  };

  if (routes[type]) {
    console.log(`Navigating to: ${routes[type]}`);
    uni.navigateTo({
      url: routes[type],
      success: () => {
        console.log('Navigation successful');
      },
      fail: (err) => {
        console.error('Navigation failed:', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  } else {
    console.error(`Invalid route type: ${type}`);
    uni.showToast({
      title: '无效的页面类型',
      icon: 'none'
    });
  }
};

const monitorData = computed(() => [
  {
    title: '血氧监测',
    status: bloodOxygenStatus.value,
    statusClass: getStatusClass('bloodOxygen'),
    value: currentBloodOxygen.value,
    unit: '%',
    footerText: `当前状态: ${bloodOxygenStatus.value}`,
    footerButton: {
      label: '查看详情',
      action: () => navigateToDetail('bloodOxygen')
    },
  },
  {
    title: '心率监测',
    status: heartRateStatus.value,
    statusClass: getStatusClass('heartRate'),
    value: currentHeartRate.value,
    unit: '次/分',
    trend: { 
      type: heartRateTrend.value.type, 
      text: `较昨日 ${heartRateTrend.value.value}%` 
    },
    footerButton: {
      label: '查看详情',
      action: () => navigateToDetail('heartRate')
    }
  },
  {
    title: '血压监测',
    status: bloodPressureStatus.value,
    statusClass: getStatusClass('bloodPressure'),
    value: `${currentBloodPressure.value.systolic}/${currentBloodPressure.value.diastolic}`,
    unit: 'mmHg',
    footerButton: { 
      label: '查看详情', 
      action: () => navigateToDetail('bloodPressure') 
    },
  },
 
]);

// 该生命周期钩子已被移除，使用页面底部的onMounted钩子替代

const getStatusClass = (category) => {
  const statusMap = {
    bloodOxygen: {
      '正常': 'success',
      '偏低': 'warning',
      '异常': 'error'
    },
    heartRate: {
      '正常': 'success',
      '偏高': 'warning',
      '偏低': 'warning',
      '异常': 'error'
    },
    bloodPressure: {
      '正常': 'success',
      '正常偏高': 'warning',
      '高血压': 'error',
      '低血压': 'warning'
    }
  }

  const currentStatus = {
    bloodOxygen: bloodOxygenStatus.value,
    heartRate: heartRateStatus.value,
    bloodPressure: bloodPressureStatus.value
  }[category]

  return statusMap[category][currentStatus] || 'default'
}


// 页面加载时获取最新数据
onMounted(async () => {
  try {
    await healthStore.fetchRealtimeData(currentUserId.value)
    await healthStore.fetchSleepDetail(currentUserId.value, 'day');
    await healthStore.fetchActivityDetail(currentUserId.value, 'day');
  } catch (error) {
    console.error('Error loading data:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  }
});
</script>

<style lang="scss">
.health-container {
  padding: 20rpx;
  background-color: #f8fafc;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .logo {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }

  .title {
    flex: 1;
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }

  .badge {
    background-color: #f56c6c;
    color: white;
    border-radius: 50%;
    width: 36rpx;
    height: 36rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
  }
}

.tabs {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  margin: 20rpx 0;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 30rpx;
    color: #666;

    &.active {
      color: #409eff;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 6rpx;
        background: #409eff;
        border-radius: 3rpx;
      }
    }
  }
}

.content {
  padding-bottom: 40rpx;
}

.overview-cards {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
}

.overview-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }

  .card-content {
    flex: 1;
  }

  .card-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 12rpx;
  }

  .card-value {
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 12rpx;

    .unit {
      font-size: 24rpx;
      color: #999;
      margin-left: 8rpx;
    }
  }

  .card-footer {
    display: flex;
    flex-direction: column;
    gap: 4rpx;

    .time, .distance {
      font-size: 24rpx;
      color: #666;

      .unit {
        font-size: 20rpx;
        color: #999;
        margin-left: 4rpx;
      }
    }

    .label {
      font-size: 20rpx;
      color: #999;
    }
  }

  .card-icon {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(64, 158, 255, 0.1);
    border-radius: 50%;
    margin-left: 20rpx;
  }

  &.activity .card-icon {
    background: rgba(103, 194, 58, 0.1);
  }
}

.tab-content {
  padding: 20rpx 0;
}

.monitor-cards {
  display: grid;
  grid-template-columns: 1fr;
  gap: 24rpx;
}

.sleep-stats {
  display: flex;
  justify-content: center; // 水平居中
  align-items: center; // 垂直居中
  margin: 24rpx 0;

  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 20rpx;

    .stat-value {
      font-size: 54rpx;
      font-weight: bold;
      color: #409eff;
    }

    .stat-label {
      font-size: 26rpx;
      color: #999;
      margin-top: 8rpx;
    }
  }
}

.activity-stats {
  display: flex;
  justify-content: space-around;
  margin: 30rpx 0;

  .activity-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .activity-value {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
    }

    .activity-label {
      font-size: 26rpx;
      color: #999;
      margin-top: 8rpx;
    }
  }
}

.activity-chart {
  height: 200rpx;
  margin-top: 20rpx;
  background-color: #f5f7fa;
  border-radius: 12rpx;
}

.sleep-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;

  .sleep-time {
    font-size: 26rpx;
    color: #666;
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.detail-btn {
  font-size: 24rpx;
  color: #409eff;
  background: none;
  border: none;
  padding: 10rpx 20rpx;
  
  &:active {
    opacity: 0.8;
  }
}
</style>
